package com.aimaterials.resource.util;

import java.math.BigInteger;
import java.util.Stack;

/**
 * @Author maplemei
 * @Date 2019/5/29 5:19 PM
 * @Version 1.0
 */
public class MathUtils {
    // 理论上支持62进制的转换, 当然可以自己添加一些其他符号来增加进制数
    private static final String TARGET_STR = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
    private static final char[] chs = TARGET_STR.toCharArray();
    private static final BigInteger INTEGER0 = new BigInteger("0");


    /**
     * 10进制转任意进制
     */
    public static String numToRadix(String number, int radix) {
        if(radix < 0 || radix > TARGET_STR.length()){
            radix = TARGET_STR.length();
        }

        BigInteger bigNumber = new BigInteger(number);
        BigInteger bigRadix = new BigInteger(radix + "");

        Stack<Character> stack = new Stack<>();
        StringBuilder result = new StringBuilder(0);
        while (!bigNumber.equals(INTEGER0)) {
//            System.out.println("bigRadix:"+bigRadix);
//            System.out.println("bigNumber.remainder(bigRadix).intValue():"+bigNumber.remainder(bigRadix).intValue());
            stack.add(chs[bigNumber.remainder(bigRadix).intValue()]);
            bigNumber = bigNumber.divide(bigRadix);
        }
        for (; !stack.isEmpty(); ) {
            result.append(stack.pop());
        }
        return result.length() == 0 ? "0" : result.toString();
    }

    /**
     * 任意进制转10进制
     */
    public static String radixToNum(String number, int radix){
        if(radix < 0 || radix > TARGET_STR.length()){
            radix = TARGET_STR.length();
        }
        if (radix == 10) {
            return number;
        }

        char ch[] = number.toCharArray();
        int len = ch.length;

        BigInteger bigRadix = new BigInteger(radix + "");
        BigInteger result = new BigInteger("0");
        BigInteger base = new BigInteger("1");


        for (int i = len - 1; i >= 0; i--) {
            BigInteger index = new BigInteger(TARGET_STR.indexOf(ch[i]) + "");
            result = result.add(index.multiply(base)) ;
            base = base.multiply(bigRadix);
        }

        return result.toString();
    }


    /**
     * 任意进制之间的互相转换, 先将任意进制转为10进制, 然后在转换为任意进制
     */
    public static String transRadix(String num, int fromRadix, int toRadix) {
        return numToRadix(radixToNum(num, fromRadix), toRadix);
    }

    public static void main(String[] args) {
//        //res: a
//        System.out.println(transRadix("28BR1GU57LNYD.5V3X7IXG9G", 45, 16));

        System.out.println(transRadix("FE1FFDC6914411EB87CB0242AC110002", 16, 45));
//        28CH72Z+N6FXWF*S-P0ILLWZ
//        28CH72Z+N6FXWF*S-P0ILLW:
//        28CH72Z+N6FXWF*S-P0ILLX0

    }

}

